<?php

namespace App\Repositories;

use App\Models\AdminPrivilege;
use App\Models\Privilege;
use Exception;
use Carbon\Carbon;
use App\Models\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Exceptions\GeneralException;

/**
 * 用户模块Repository
 *
 * Date: 2018/05/18
 * @author Tenny
 * @package App\Repositories
 */
class AdminRepository extends BaseRepository
{
    /**
     * 定义模型类
     *
     * Date: 2018/05/18
     * @author Tenny
     * @return mixed|string
     */
    public function model()
    {
        return Admin::class;
    }

    /**
     * 获取共派管理员列表
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $name
     * @param $created_at
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getAdmins($name = false, $created_at = false, $limit = 15)
    {
        $query = Admin::query();
        if ($name !== false) {
            $query->where('name', 'like', '%' . $name . '%');
        }
        if ($created_at) {
            $query->whereBetween('created_at', $created_at);
        }
        $admins = $query
            ->with(["privileges" => function ($query) {
                $query->select('modular_name')->distinct('modular_name');
            }])
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        if ($admins->isNotEmpty()) {
            foreach ($admins as &$user) {
                $str = '';
                foreach ($user['privileges'] as $permission) {
                    if ($str == null) {
                        $str .= '、' . $permission['modular_name'];
                    } elseif (FALSE === stripos($str, $permission['modular_name'])) {
                        $str .= '、' . $permission['modular_name'];
                    }
                }
                $user['permission'] = trim($str, '、');
                unset($user['privileges']);
            }
        }
        return $admins;
    }

    /**
     * 根据uid获取用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $uid
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder
     * @throws GeneralException
     */
    public function getAdminsDetails($uid, $limit = 15)
    {
        $query = Admin::query();
        $admin = $query
            ->with(["privileges"])
            ->where('id', $uid)
            ->first();
        $data = [];
        if ($admin) {
            if (optional($admin)->is_owner !== null && $admin->is_owner == 1) {
                $admin->permission = $this->getPermissions();
                $admin->allPermission = $this->getPermissions();
            } else {
                $permissionLists = $admin->privileges->toArray();
                if (is_array($permissionLists) && count($permissionLists) > 0) {
                    foreach ($permissionLists as $permission) {
                        if ($this->deep_in_array($permission['modular_name'], $data)) {
                            foreach ($data as $k => $value) {
                                if ($value['modular_name'] == $permission['modular_name']) {
                                    $data[$k]['list'][] = [
                                        'id' => $permission['id'],
                                        'name' => $permission['action_name']
                                    ];
                                }
                            }
                        } else {
                            $data[] = [
                                'modular_name' => $permission['modular_name'],
                                'list' => [
                                    [
                                        'id' => $permission['id'],
                                        'name' => $permission['action_name']
                                    ],
                                ]
                            ];
                        }
                    }
                }

                $admin->permission = $data;
                $admin->allPermission = $this->getPermissions();
            }
            $userLogRepository = new UserLogRepository;
            $admin_log = $userLogRepository->getLog($uid, false, 2, false, $limit);
            $admin->admin_log = $admin_log;
            unset($admin->privileges, $data, $admin_log);
        }
        return $admin;
    }

    /**
     * 获取权限列表
     *
     * Date: 2018/06/09
     * @author Tenny
     * @return array
     */
    public function getPermissions()
    {
        $permissions = Privilege::get()->toArray();;
        $res = [];
        if (is_array($permissions) && count($permissions) > 0) {
            foreach ($permissions as $k => $permission) {
                $key = array_search($permission['modular_name'], $res);
                if ($this->deep_in_array($permission['modular_name'], $res)) {
                    foreach ($res as $k => $value) {
                        if ($value['modular_name'] == $permission['modular_name']) {
                            $res[$k]['list'][] = [
                                'id' => $permission['id'],
                                'name' => $permission['action_name']
                            ];
                        }
                    }
                } else {
                    $res[] = [
                        'modular_name' => $permission['modular_name'],
                        'list' => [
                            [
                                'id' => $permission['id'],
                                'name' => $permission['action_name']
                            ],
                        ]
                    ];

                }
            }
        }
        return $res;
    }

    /**
     * 获取根据账户id权限字符串
     *
     * Date: 2018/06/09
     * @author Tenny
     * @param $admin_id
     * @return string
     */
    public function getPermissionsById($admin_id)
    {
        $permissions = AdminPrivilege::with(['privilege'])
            ->where('admin_id', '=', $admin_id)
            ->get()
            ->toArray();
        $str = '';
        if (is_array($permissions) && count($permissions) > 0) {
            foreach ($permissions as $permission) {
                if ($permission['privilege']) {
                    if ($str == null) {
                        $str .= '、' . $permission['privilege']['modular_name'];
                    } elseif (FALSE === stripos($str, $permission['privilege']['modular_name'])) {
                        $str .= '、' . $permission['privilege']['modular_name'];
                    }
                }
            }
            $str = trim($str, '、');
        }
        return $str;
    }

    /**
     * 修改用户密码
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param $oldPassword
     * @param $newPassword
     * @param Admin $admin
     * @return bool
     * @throws \Throwable
     */
    public function modifyPassword($oldPassword, $newPassword, Admin $admin): bool
    {
        $result = $this->verifyPassword($admin, $oldPassword);

        if ($result) {
            $admin->password = $newPassword;
            return $admin->saveOrFail();
        }

        return false;
    }

    /**
     * 修改头像
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param string $path
     * @param Admin $admin
     * @return bool
     * @throws \Throwable
     */
    public function modifyAvatar(string $path, Admin $admin): bool
    {
        $admin->avatar = $path;
        return $admin->saveOrFail();
    }

    /**
     * 验证用户密码
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param Admin $admin
     * @param $plain
     * @return bool
     */
    public function verifyPassword(Admin $admin, $plain)
    {
        return Hash::check($plain, $admin->getAuthPassword());
    }

    /**
     * 更新用户身份信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param array $attributes
     * @return \Illuminate\Database\Eloquent\Model
     * @throws GeneralException
     */
    public function modifyIdentification(array $attributes)
    {
        try {
            return Identification::updateOrCreate($attributes, array_values($attributes));
        } catch (Exception $exception) {
            throw new GeneralException('更新用户身份信息失败');
        }
    }

    /**
     * 多维in_array
     *
     * Date: 2018/06/11
     * @author Tenny
     * @param $value
     * @param $array
     * @return boolean
     */
    public function deep_in_array($value, $array)
    {
        if (is_array($array) && count($array) > 0) {
            foreach ($array as $item) {
                if (!is_array($item)) {
                    if ($item == $value) {
                        return true;
                    } else {
                        continue;
                    }
                }
                if (in_array($value, $item)) {
                    return true;
                } else if ($this->deep_in_array($value, $item)) {
                    return true;
                }
            }
        }
        return false;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}
